import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '@/router'

export const useTagsStore = defineStore('tags', () => {
  // 已打开的标签页
  const visitedTags = ref([
    // 默认首页标签
    {
      path: '/dashboard/workspace',
      title: '工作台',
      name: 'Workspace',
      affix: true // 固定标签（不可关闭）
    }
  ])
  
  // 当前激活的标签
  const activeTag = ref('/dashboard/workspace')
  
  // 添加标签
  const addTag = (route) => {
    const { path, meta, name } = route
    
    // 如果标签已存在，不重复添加
    if (visitedTags.value.some(tag => tag.path === path)) {
      return
    }
    
    // 添加新标签
    visitedTags.value.push({
      path,
      title: meta.title || '未命名',
      name: name,
      affix: false
    })
  }
  
  // 关闭标签
  const closeTag = (path) => {
    for (let i = 0, len = visitedTags.value.length; i < len; i++) {
      if (visitedTags.value[i].path === path) {
        visitedTags.value.splice(i, 1)
        break
      }
    }
    
    // 如果关闭的是当前激活标签，则激活前一个标签
    if (activeTag.value === path) {
      const latestTag = visitedTags.value[visitedTags.value.length - 1]
      if (latestTag) {
        activeTag.value = latestTag.path
        router.push(latestTag.path)
      } else {
        // 如果没有其他标签，则跳转到首页
        router.push('/')
      }
    }
  }
  
  // 关闭其他标签
  const closeOtherTags = (path) => {
    visitedTags.value = visitedTags.value.filter(tag => {
      return tag.affix || tag.path === path
    })
    
    if (activeTag.value !== path) {
      activeTag.value = path
      router.push(path)
    }
  }
  
  // 关闭所有标签
  const closeAllTags = () => {
    // 保留固定标签
    visitedTags.value = visitedTags.value.filter(tag => tag.affix)
    
    // 如果没有固定标签，则跳转到首页
    if (visitedTags.value.length === 0) {
      router.push('/')
    } else {
      const firstTag = visitedTags.value[0]
      activeTag.value = firstTag.path
      router.push(firstTag.path)
    }
  }
  
  // 设置当前激活标签
  const setActiveTag = (path) => {
    activeTag.value = path
  }
  
  return {
    visitedTags,
    activeTag,
    addTag,
    closeTag,
    closeOtherTags,
    closeAllTags,
    setActiveTag
  }
}, {
  persist: {
    key: 'vue3-demo-tags',
    storage: localStorage,
    paths: ['visitedTags', 'activeTag']
  }
}) 